﻿using System;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using Casamiel.Common;
using Casamiel.Domain.Response;
using MediatR;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;
using Newtonsoft.Json;

namespace Casamiel.Application.Commands
{
	/// <summary>
	/// 
	/// </summary>
	public sealed class MemberExtInfoCommandHandler: BaseCommandHandler,IRequestHandler<MemberExtInfoCommand,BaseResult<string>>
	{
		private readonly IServiceScopeFactory _scopeFactory;

		/// <summary>
		/// 
		/// </summary>
		/// <param name="serviceScopeFactory"></param>
		/// <param name="netICService"></param>
		/// <param name="httpClientFactory"></param>
		/// <param name="settings"></param>
		public MemberExtInfoCommandHandler(IServiceScopeFactory serviceScopeFactory,INetICService netICService, IHttpClientFactory httpClientFactory, IOptionsSnapshot<CasamielSettings> settings) : base(netICService, httpClientFactory, settings)
		{
			
			_scopeFactory = serviceScopeFactory;
		}

		/// <summary>
		/// 
		/// </summary>
		/// <param name="request"></param>
		/// <param name="cancellationToken"></param>
		/// <returns></returns>
		public async Task<BaseResult<string>> Handle(MemberExtInfoCommand request, CancellationToken cancellationToken)
		{
			if (request is null) {
				throw new ArgumentNullException(nameof(request));
			}
			BizInfologger.Trace($"MemberExtInfo:{JsonConvert.SerializeObject(request)}");
			using var scope = _scopeFactory.CreateScope();
			
			var _memberService = scope.ServiceProvider.GetRequiredService<IMemberService>();
			var _cardService = scope.ServiceProvider.GetRequiredService<IMemberCardService>();

			var member = await _memberService.FindAsync<ICasaMielSession>(request.Mobile).ConfigureAwait(false);
			request.RegisterTime = member.CreateDate.Value;
			member.Nick = request.RealName;
			 
			member.InvitationCode = request.InvitationCode;
			var url = "v3/MemberCard/SaveCardMember";
			var cardinfo = await _cardService.FindAsync<ICasaMielSession>(request.Mobile, false).ConfigureAwait(false);
			if (cardinfo != null) {
				request.CardNo = cardinfo?.CardNO;
				request.CardType = Convert.ToInt16(cardinfo.CardType);
				request.BindSource = cardinfo.Source == 15 ? 1 : 2;
				request.BindTime = cardinfo.BindTime;


			}

			await _memberService.UpdateAsync<ICasaMielSession>(member).ConfigureAwait(false);
 
			//var data = new { mobile = request.Mobile, orderCode = request.OrderCode };
			var result = await PostThirdApiAsync<string>(url, JsonConvert.SerializeObject(request)).ConfigureAwait(false);
			return result;
		}
	}
}
